// Copyright 2010 Google Inc. All Rights Reserved.

/**
 * @fileoverview Batches multiple individual RPC requests into a single HTTP
 * request.
 *
 * @author monsur@google.com (Monsur Hossain)
 */

goog.provide('googleapis.Batch');


/**
 * @constructor
 */
googleapis.Batch = function() {
  this.callbackMap_ = {};
  this.batch_ = osapi.newBatch();
};


/**
 * @param {string} key A unique key to identify this request.
 * @param {Object} request The request object.
 * @param {Function} callback The function to call with the response.
 * @return {googleapis.Batch} This object.
 */
googleapis.Batch.prototype.add = function(key, request, callback) {
  this.callbackMap_[key] = callback;
  this.batch_.add(key, request);
  return this;
};


/**
 * @param {Function} callback The function to call on any batch responses that
 *     don't have an individual callback.
 */
googleapis.Batch.prototype.execute = function(callback) {
  var that = this;
  var callbackWrapper = function(batchResult) {
    var orphanResults = {};
    var hasOrphanResults = false;
    for (var key in batchResult) {
      if (!batchResult.hasOwnProperty(key)) {
        continue;
      }
      var result = batchResult[key];
      var resultCallback = that.callbackMap_[key];
      if (resultCallback) {
        resultCallback(result);
      } else {
        orphanResults[key] = result;
        hasOrphanResults = true;
      }
    }
    if (hasOrphanResults && callback) {
      callback(orphanResults);
    }
  };

  this.batch_.execute(callbackWrapper);
};
